package com.fbt.transfer.app.driver.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;

/**
 * 网络工具类
 */
public class NetworkUtils {

  private static final String TAG = NetworkUtils.class.getSimpleName();

  /**
   * 检查网络是否可用
   *
   * @param context 上下文
   * @return 网络是否可用
   */
  public static boolean isNetworkAvailable(Context context) {
    if (context == null) {
      return false;
    }

    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(
        Context.CONNECTIVITY_SERVICE);
    if (connectivityManager == null) {
      return false;
    }

    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    if (networkInfo == null) {
      return false;
    }

    // 检查网络是否连接
    if (!networkInfo.isConnected()) {
      return false;
    }

    // 检查网络类型
    int type = networkInfo.getType();
    switch (type) {
      case ConnectivityManager.TYPE_WIFI:
        return isWifiAvailable(context);
      case ConnectivityManager.TYPE_MOBILE:
        return isMobileAvailable(context);
      default:
        return false;
    }
  }

  /**
   * 检查WiFi是否可用
   *
   * @param context 上下文
   * @return WiFi是否可用
   */
  private static boolean isWifiAvailable(Context context) {
    WifiManager wifiManager = (WifiManager) context.getApplicationContext()
        .getSystemService(Context.WIFI_SERVICE);
    if (wifiManager == null) {
      return false;
    }
    return wifiManager.isWifiEnabled();
  }

  /**
   * 检查移动网络是否可用
   *
   * @param context 上下文
   * @return 移动网络是否可用
   */
  private static boolean isMobileAvailable(Context context) {
    TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(
        Context.TELEPHONY_SERVICE);
    if (telephonyManager == null) {
      return false;
    }
    return telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED;
  }
} 